package pl.put.to.regression.linearprogramming;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ReusableVariablesVector {
	private List<String> variables;
	private Set<Integer> lastModifiedVariables;

	public ReusableVariablesVector(int size) {
		variables = new ArrayList<String>();
		lastModifiedVariables = new HashSet<Integer>();

		for (int i = 0; i < size; ++i) {
			variables.add("0");
		}
	}

	public void clearVector() {
		for (Integer dirtyVariable : lastModifiedVariables) {
			variables.set(dirtyVariable, "0");
		}

		lastModifiedVariables.clear();
	}

	public void setVariable(int position, String value) {
		variables.set(position, value);

		lastModifiedVariables.add(position);
	}

	public void clearAndSetVariables(Map<Integer, String> variablesValues) {
		clearVector();

		for (Integer position : variablesValues.keySet()) {
			if (position < variables.size()) {
				setVariable(position, variablesValues.get(position));
			}
		}
	}

	public void clearAndSetRange(int fromIndex, int toIndex, String value) throws IllegalArgumentException {
		if (fromIndex < 0 || toIndex >= variables.size() || toIndex < fromIndex) {
			throw new IllegalArgumentException("Indexes out of range. Should be between 0 and " + variables.size());
		}

		clearVector();

		for (int i = fromIndex; i <= toIndex; ++i) {
			setVariable(i, value);
		}
	}

	public List<String> getVariables() {
		return Collections.unmodifiableList(variables);
	}

	@Override
	public String toString() {
		StringBuilder result = new StringBuilder();

		for (String variable : variables) {
			result.append(variable).append(" ");
		}

		result.deleteCharAt(result.length() - 1);

		return result.toString();
	}
}
